<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue UUID Send with Axios</title>
    <!-- 引入Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- 引入Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<style>
    #app {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin-top: 100px;
    }
</style>
<body>
<div id="app">
    <button @click="qrCodeLogin">扫码登陆</button>
    <p>UUID: {{ uuid }}</p>

    <img :src="qrCodeBase64" alt="" v-if="qrCodeBase64">


</div>

<script>
    // Vue实例
    new Vue({
        el: '#app',
        data: {
            uuid: '',
            requestUrl: 'https://52fb5f31.r28.cpolar.top',
            qrCodeBase64: null
        },
        created() {
            // 生成伪UUID
            this.uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });


        },
        methods: {
            qrCodeLogin() {
                // 调用二维码登录方法
                axios.get(this.requestUrl+'/generateQrCode?login_uuid=' + this.uuid)
                    .then(response => {
                        console.log('Success:', response.data);
                        this.qrCodeBase64 = response.data;
                        this.checkQrCode();
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            },
            checkQrCode() {
                //轮训请求后端接口,如果后端返回成功,则结束轮训
                //轮训2s一次
                //如果后端返回失败,则继续轮训
                //如果后端返回成功,则结束轮训
                let intervalId = null;
                const poll = () => {
                    axios.get(this.requestUrl+'/checkQrCode?login_uuid=' + this.uuid)
                        .then(response => {
                            console.log('Success:', response.data);
                            if (response.data === true) {
                                this.qrCodeBase64 = null;
                                alert("登录成功")
                                clearInterval(intervalId);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                }


                intervalId = setInterval(poll, 2000);
            }
        }
    });
</script>
</body>
</html>